package com.mzw.project.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mzw.mzwcommon.model.entity.User;
import com.mzw.project.bizmq.BiMessageProducer;
import com.mzw.project.common.*;
import com.mzw.project.model.entity.SeckillVoucher;
import com.mzw.project.model.entity.VoucherOrder;
import com.mzw.project.service.SeckillVoucherService;
import com.mzw.project.service.UserService;
import com.mzw.project.service.VoucherOrderService;
import com.mzw.project.mapper.VoucherOrderMapper;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Collections;

import static com.mzw.project.constant.UserConstant.USER_LOGIN_STATE;

/**
* @author L1nAn
* @description 针对表【voucher_order】的数据库操作Service实现
* @createDate 2023-09-17 11:40:02
*/
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder>
    implements VoucherOrderService{

    @Resource
    private SeckillVoucherService seckillVoucherService;

    @Resource
    private RedisIdWorker redisIdWorker;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private UserService userService;

    @Resource
    private BiMessageProducer biMessageProducer;
    @Resource
    private RedissonClient redissonClient;
    //加载Lua脚本
    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;// 给这个属性进行初始化，在静态代码块中  SECKILL_SCRIPT 这是脚本的名字
    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        //配置脚本文件，指定文件地址
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));//ClassPathResource 下不就是resource下的目录吗
        //配置返回值的类型,和上面是对应的
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    @Override
    public BaseResponse<Long> seckillCoucher(Long voucherId, HttpServletRequest request) {
        // 1、查询优惠券
        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
        // 2.判断秒杀是否开始
        if (voucher.getBeginTime().isAfter(LocalDateTime.now())) {
            // 尚未开始
            return ResultUtils.error(ErrorCode.FORBIDDEN_ERROR, "秒杀尚未开始");
        }
        // 3.判断秒杀是否结束
        if (voucher.getEndTime().isBefore(LocalDateTime.now())) {
            return ResultUtils.error(ErrorCode.FORBIDDEN_ERROR, "秒杀已经结束");
        }
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        Long userId = currentUser.getId();
        // 执行lua脚本,判断库存是否充足
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), userId.toString()
        );
        int r = result.intValue();
        if (r != 0) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR, r == 1 ? "库存不足" : "不能重复下单");
        }
//
//        //6.创建订单
//        VoucherOrder voucherOrder = new VoucherOrder();
//        // 6.1.订单id
        long orderId = redisIdWorker.nextId("order");
        // 把用户id,订单id,还有优惠券id一块发送到消息队列，接口id是根据voucherid 得到的，因为每一个接口都有一个对应的id
        String message = userId + "," + orderId + "," + voucherId;
        biMessageProducer.sendMessage(message);
//        voucherOrder.setId(orderId);
//        voucherOrder.setUserId(userId);
//        // 6.3.代金券id
//        voucherOrder.setVoucherId(voucherId);
//        save(voucherOrder);
        // 发送消息队列，然后进行创建订单的处理
        // 同时将消息发送至延时队列，如果一天之内用户没有兑换次数，那么此抵用券就将作废
        biMessageProducer.sendDelayedMessage(message);
        return ResultUtils.success(orderId);
    }

    @Override
    @Transactional
    public void createVoucherOrder(VoucherOrder voucherOrder) {
        Long userId = voucherOrder.getUserId();
        Long voucherId = voucherOrder.getVoucherId();
        Long interfaceInfoId = voucherOrder.getInterfaceInfoId();
        // 创建锁对象
        RLock redisLock = redissonClient.getLock("lock:order:" + userId);
        // 尝试获取锁
        boolean isLock = redisLock.tryLock();
        // 判断
        if (!isLock) {
            // 获取锁失败，直接返回失败或者重试
            log.error("不允许重复下单！");
            return;
        }
        try {
            // 5.1.查询订单
            long count = query().eq("userId", userId).eq("interfaceInfoId", interfaceInfoId).eq("voucherId", voucherId).count();
            // 5.2.判断是否存在
            if (count > 0) {
                // 用户已经购买过了
                log.error("不允许重复下单！");
                return;
            }

            // 6.扣减库存
            boolean success = seckillVoucherService.update()
                    .setSql("stock = stock - 1") // set stock = stock - 1
                    .eq("voucherId", voucherId).gt("stock", 0) // where id = ? and stock > 0
                    .update();
            if (!success) {
                // 扣减失败
                log.error("库存不足！");
                return;
            }
            // 7.创建订单
            save(voucherOrder);
        } finally {
            // 释放锁
            redisLock.unlock();
        }
    }
}




